package me.pinion.service;

import com.jfinal.kit.PathKit;
import com.jfinal.upload.UploadFile;
import me.pinion.controller.Controller;
import me.pinion.kit.MimeKit;
import me.pinion.model.Attach;
import me.pinion.oss.BucketKit;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Calendar;

public class AttachService extends Service{


    public Attach saveAttach(Controller controller){
        return this.saveAttach(controller, "file");
    }

    public Attach saveAttach(Controller controller, String paramName){
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int date = calendar.get(Calendar.DATE);
        String path = "upload/" + year + "/"
                + (month > 9 ? month : "0" + month)
                + (date > 9 ? date : "0" + date) + "/";

        UploadFile uploadFile = controller.getFile(paramName, PathKit.getWebRootPath() + "/" + path, 1024 * 1024 * 1024);

        File file = uploadFile.getFile();

        Attach attach = new Attach();
        attach.set("name", file.getName());
        attach.set("type", MimeKit.getType(file));
        attach.set("size", file.length());
        attach.set("url", path + file.getName());
        try {
            BucketKit.upload(file, path + file.getName());
            attach.save();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return attach;
    }

}
